package cn.rkylin.oms.aftersale.event.service.impl;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.PageInfo;

import cn.rkylin.core.ApolloMap;
import cn.rkylin.core.service.ApolloService;
import cn.rkylin.oms.aftersale.event.dao.IAfterSaleEventDAO;
import cn.rkylin.oms.aftersale.event.domain.AfterSaleEvent;
import cn.rkylin.oms.aftersale.event.service.IAfterSaleEventService;
import cn.rkylin.oms.aftersale.event.vo.AfterSaleEventVO;
import cn.rkylin.oms.common.consts.EventStatus;
import cn.rkylin.oms.common.consts.YesNoConst;
import cn.rkylin.oms.common.context.CurrentUser;
import cn.rkylin.oms.common.context.WebContextFactory;
import cn.rkylin.oms.common.utils.CodeUtil;
import cn.rkylin.oms.order.dao.IOrderDAO;
import cn.rkylin.oms.order.service.IOrderService;
import cn.rkylin.oms.order.vo.OrderVO;
import cn.rkylin.oms.system.project.service.ProjectManagerService;
import cn.rkylin.oms.system.project.vo.ProjectVO;
import cn.rkylin.oms.system.shop.service.IShopService;
import cn.rkylin.oms.system.shop.vo.ShopVO;
import cn.rkylin.oms.system.user.service.IUserService;
import cn.rkylin.oms.system.user.vo.UserVO;

/**
 * 类名:AfterSaleEventServiceImpl <br/>
 * 作用: 售后事件服务层. <br/>
 * 创建原因: 售后事件服务层. <br/>
 * 创建时间: 2017年9月25日 下午1:42:17 <br/>
 *
 * @author zhanghao
 * @version v1.0
 */
@Service
public class AfterSaleEventServiceImpl extends ApolloService implements IAfterSaleEventService {

    private static final String STATEMENT_SELECT_COUNT_BY_STATUS = "selectEventCounts";

    /**
     * eventDao:售后事件数据层
     */
    @Autowired
    private IAfterSaleEventDAO eventDao;
    /**
     * orderService：订单服务层
     */
    @Autowired
    private IOrderService orderService;

    /**
     * eventDAO：售后事件数据层
     */
    @Autowired
    private IAfterSaleEventDAO eventDAO;
    /**
     * orderService:订单服务层
     */
    @Autowired
    public IOrderDAO orderDao;

    /**
     * shopService:店铺服务层
     */
    @Autowired
    public IShopService shopService;

    /**
     * 项目服务层
     */
    @Autowired
    private ProjectManagerService projectManagerService;

    /**
     * 用户业务服务对象
     */
    @Autowired
    private IUserService userService;

    /**
     * 构造器：AfterSaleEventServiceImpl.
     */
    public AfterSaleEventServiceImpl() {

    }

    /**
     * queryEventList:根据查询条件查询售后事件列表.
     */
    @Override
    public PageInfo<AfterSaleEventVO> queryEventList(int page, int rows, AfterSaleEventVO event) throws Exception {
        return eventDao.selectPagedByCondition(page, rows, event);
    }

    /**
     * findCounts：事件的各种Count
     */
    public List<AfterSaleEventVO> findCounts(AfterSaleEventVO param) throws Exception {
        List<AfterSaleEventVO> list = findPage(STATEMENT_SELECT_COUNT_BY_STATUS, param);
        return list;
    }

    /**
     * validateEventDealer:如果事件处理人是userId，则返回true；否则返回False.
     */
    @Override
    public boolean validateEventDealer(String userId, String eventId) throws Exception {
        boolean returnValue = false;
        AfterSaleEvent event = queryEventById(eventId);
        if (StringUtils.isNotEmpty(userId) && userId.equals(event.getFactDealUserId())) {
            returnValue = true;
        }
        return returnValue;
    }

    /**
     * queryEventById:根据ID查询售后事件.
     */
    @Override
    public AfterSaleEventVO queryEventById(String queryEventId) throws Exception {
        AfterSaleEventVO returnObject = new AfterSaleEventVO();
        AfterSaleEventVO eventVO = new AfterSaleEventVO();
        if (StringUtils.isNotEmpty(queryEventId)) {
            eventVO.setEventId(queryEventId);
            eventVO.setDeleted(YesNoConst.NO);
            List<AfterSaleEventVO> resultList = eventDao.selectByCondition(eventVO);
            if (resultList.size() > 0) {
                returnObject = resultList.get(0);
            }
        }
        return returnObject;
    }

    /**
     * queryEventByCode:根据售后事件编号查询售后事件. <br/>
     */
    @Override
    public AfterSaleEvent queryEventByCode(String Code) throws Exception {
        AfterSaleEvent returnObject = null;

        AfterSaleEventVO eventVO = new AfterSaleEventVO();
        if (StringUtils.isEmpty(Code)) {
            eventVO.setEventCode(Code);
            eventVO.setDeleted(YesNoConst.NO);
            List<AfterSaleEventVO> resultList = eventDao.selectByCondition(eventVO);
            if (resultList.size() > 0) {
                returnObject = resultList.get(0);
            }
        }
        return returnObject;
    }

    /**
     * queryEventByOrderId:按订单Id获取售后事件
     */
    public AfterSaleEventVO queryEventByOrderId(String orderId) throws Exception {
        AfterSaleEventVO returnObject = null;
        AfterSaleEventVO eventVO = new AfterSaleEventVO();
        if (StringUtils.isNotBlank(orderId)) {
            eventVO.setOrderId(orderId);
            eventVO.setDeleted("n");
            List<AfterSaleEventVO> resultList = eventDao.selectByCondition(eventVO);
            if (resultList != null && resultList.size() > 0) {
                returnObject = resultList.get(0);
            }
        }
        return returnObject;
    }

    /**
     * saveEvent:保存售后事件
     */
    @Override
    @Transactional
    public String saveEvent(AfterSaleEventVO eventVO) throws Exception {
        String returnMsg = "缺少订单信息";
        // 根据来源单号查询订单
        String orderId = eventVO.getOrderId();
        OrderVO order = orderDao.findById(orderId);
        if (StringUtils.isEmpty(eventVO.getEventId())) {
            /**
             * insert:新增售后事件<br/>
             * 新增售后事件必须指定订单，如果没有订单信息不能生成售后事件.<br/>
             * 根据订单信息获取平台交易号和客户ID.<br/>
             * 售后日期应当晚于当前系统时间.<br/>
             * 新增售后事件的状态为待处理.<br/>
             */
            AfterSaleEventVO event = getEventVODetail(eventVO, order);
            int insertEvent = eventDAO.insert(event);
            if (insertEvent > 0) {
                returnMsg = "添加成功";
            }
        } else {
            // 更新售后事件
            /**
             * update:更新售后事件. <br/>
             * 只有待处理的事件可以执行更新售后事件，处理中及处理完成的不能更新售后事件.<br/>
             * 售后原因类型、指定处理人、到期时间、以及备注信息；<br/>
             */
            AfterSaleEventVO event = getEventVODetail(eventVO, order);
            int updateEvent = eventDAO.update(event);
            if (updateEvent > 0) {
                returnMsg = "修改成功";
            }
        }
        return returnMsg;
    }

    /**
     * getEventVODetail:为保存售后事件准备数据
     * 
     * @param resendVO
     * @param order
     * @return
     * @throws Exception
     */
    private AfterSaleEventVO getEventVODetail(AfterSaleEventVO eventVO, OrderVO order) throws Exception {
        // 创建时间
        if (StringUtils.isEmpty(eventVO.getEventId())) {
            eventVO.setCreateTime(new Date());
        }
        // 修改时间
        eventVO.setUpdateTime(new Date());
        // 事件Id/编号
        if (StringUtils.isEmpty(eventVO.getEventId())) {
            eventVO.setEventId(java.util.UUID.randomUUID().toString().replaceAll("-", ""));
            eventVO.setEventCode(generateReturnCodeWithType("AE", order.getShopId()));
        }
        // 获取当前登录人
        CurrentUser currentUser = WebContextFactory.getWebContext().getCurrentUser();
        // 获取当前登录人所属项目
        String projectId = currentUser.getCurrentProject().getPrjId();
        // 项目Id
        if (StringUtils.isEmpty(eventVO.getPrjId())) {
            eventVO.setPrjId(projectId);
        }
        // 企业Id
        String key = (String) currentUser.getEnterpriseMap().keySet().toArray()[0];
        if (StringUtils.isEmpty(eventVO.getEntId())) {
            eventVO.setEntId(currentUser.getEnterpriseMap().get(key));
        }
        // 事件编号
        // if (StringUtils.isEmpty(eventVO.getEventCode())) {
        // eventVO.setEventCode(generateReturnCodeWithType("AE",
        // order.getShopId()));
        // }
        // 创建人
        if (StringUtils.isEmpty(eventVO.getEventCreator())) {
            eventVO.setEventCreator(currentUser.getId());
        }
        // 到期时间 expireTime
        // 删除标记
        // eventVO.setDeleted("n");
        // 订单编号
        if (StringUtils.isEmpty(eventVO.getOrderCode())) {
            eventVO.setOrderCode(order.getOrderCode());
        }
        // 出库单编号 stockoutCode
        if (StringUtils.isEmpty(eventVO.getStockoutCode())) {
            eventVO.setStockoutCode("");
        }
        // 快递单号 lgstNo
        if (StringUtils.isEmpty(eventVO.getLgstNo())) {
            eventVO.setLgstNo("");
        }
        // 事件类型
        // 事件状态
        if (StringUtils.isEmpty(eventVO.getEventStatus())) {
            eventVO.setEventStatus(EventStatus.PENDING);
        }
        // 指派处理人
        if (StringUtils.isNotEmpty(eventVO.getPlanDealUserId())) {
            UserVO param = new UserVO();
            param.setUserId(eventVO.getPlanDealUserId());
            PageInfo<UserVO> userVOList = userService.findByWhere(1, Integer.MAX_VALUE, param, true, false, true, false);
            eventVO.setPlanDealUserName(userVOList.getList().get(0).getUserFullname());
        }
        // 买家昵称(客户ID)
        if (StringUtils.isEmpty(eventVO.getBuyerNick())) {
            eventVO.setBuyerNick(order.getBuyerNick());
        }
        // 备注
        // finishRemark
        return eventVO;
    }

    /**
     * generateReturnCodeWithType:编码生成方法 <br/>
     * 
     * @param codeType
     * @param shopId
     * @return
     * @throws Exception
     */
    private String generateReturnCodeWithType(String codeType, String shopId) throws Exception {
        ShopVO shop = shopService.getShopById(shopId);
        ApolloMap<String, Object> params = new ApolloMap<String, Object>();
        ProjectVO project = projectManagerService.findProjectById(shop.getPrjId());
        String prjShortName = project.getPrjShortName();
        String returnCode = codeType + prjShortName + CodeUtil.getCode();
        return returnCode;
    }

    /**
     * deleteAfterSaleEvent:删除售后事件.
     */
    @Override
    @Transactional
    public int deleteAfterSaleEvent(String eventIds) throws Exception {
        int returnValue = 0;
        String[] eventIdArray = StringUtils.split(eventIds, ",");
        AfterSaleEventVO record = new AfterSaleEventVO();

        record.getIdArray().addAll(Arrays.asList(eventIdArray));
        record.setDeleted(YesNoConst.YES);

        returnValue = eventDao.update(record);
        return returnValue;
    }

    /**
     * dealEvent:处理售后事件.
     */
    @Override
    @Transactional
    public int dealEvent(String eventIds) throws Exception {
        int returnValue = 0;
        String[] eventIdArray = StringUtils.split(eventIds, ",");
        AfterSaleEventVO record = new AfterSaleEventVO();

        record.getIdArray().addAll(Arrays.asList(eventIdArray));
        record.setEventStatus(EventStatus.PROCESSING);

        // 获取当前登录人
        CurrentUser currentUser = WebContextFactory.getWebContext().getCurrentUser();
        // 设置实际处理人
        record.setFactDealUserId(currentUser.getId());
        record.setFactDealUserName(currentUser.getFullName());
        returnValue = eventDao.update(record);
        return returnValue;
    }

    /**
     * cancelDealEvent：取消售后事件处理. <br/>
     */
    @Override
    @Transactional
    public int cancelDealEvent(String eventIds) throws Exception {
        int returnValue = 0;
        String[] eventIdArray = StringUtils.split(eventIds, ",");
        AfterSaleEventVO record = new AfterSaleEventVO();

        record.getIdArray().addAll(Arrays.asList(eventIdArray));
        record.setEventStatus(EventStatus.PENDING);
        record.setFactDealUserId("");
        record.setFactDealUserName("");

        returnValue = eventDao.update(record);
        return returnValue;
    }

    /**
     * completeEvent:完成售后事件.
     */
    @Override
    @Transactional
    public int completeEvent(String eventIds) throws Exception {
        int returnValue = 0;
        String[] eventIdArray = StringUtils.split(eventIds, ",");
        AfterSaleEventVO record = new AfterSaleEventVO();

        record.getIdArray().addAll(Arrays.asList(eventIdArray));
        record.setEventStatus(EventStatus.COMPLETE);

        returnValue = eventDao.update(record);
        return returnValue;
    }

    /**
     * 新增一条售后事件.
     *
     * @see cn.rkylin.oms.aftersale.event.service.IAfterSaleEventService#addAfterSaleEvent(java.lang.String,
     *      cn.rkylin.oms.aftersale.event.domain.AfterSaleEvent)
     */
    @Override
    @Transactional
    public int addAfterSaleEvent(String sysOrderId, AfterSaleEvent afterSaleEvent) throws Exception {
        int returnValue = 0;
        OrderVO orderVO = new OrderVO();
        orderVO.setOrderId(sysOrderId);
        PageInfo<OrderVO> orderList = orderService.findByWhere(1, 1, orderVO);
        if (orderList.getList().size() > 0) {
            CurrentUser currentUser = WebContextFactory.getWebContext().getCurrentUser();
            Date now = new Date();
            String key = (String) currentUser.getEnterpriseMap().keySet().toArray()[0];
            afterSaleEvent.setEntId(currentUser.getEnterpriseMap().get(key));

            afterSaleEvent.setCreateTime(now);
            afterSaleEvent.setDeleted("n");
            afterSaleEvent.setUpdateTime(now);
            String eventId = java.util.UUID.randomUUID().toString().replaceAll("-", "");
            // TODO: 获取售后事件的code
            // afterSaleEvent.setEventCode(CodeUtil.getCode(workerId,
            // datacenterId));
            afterSaleEvent.setEventId(eventId);
            afterSaleEvent.setEventStatus(EventStatus.PENDING);
            // TODO: 设置售后事件的类型
            // afterSaleEvent.setEventType(eventType);
            // 将实际执行人设置为空
            afterSaleEvent.setFactDealUserId("");
            afterSaleEvent.setPrjId(currentUser.getCurrentProject().getPrjId());

            OrderVO order = orderList.getList().get(0);
            afterSaleEvent.setBuyerNick(order.getBuyerNick());
            afterSaleEvent.setOrderCode(order.getOrderCode());
            afterSaleEvent.setOrderId(sysOrderId);

            // TODO: 设置出库单号
            // afterSaleEvent.setStockoutCode();

            // 保存售后事件
            returnValue = eventDao.insert(afterSaleEvent);
        }

        return returnValue;
    }

    /**
     * updateAfterSaleEvent:售后事件更新.
     */
    @Override
    @Transactional
    public int updateAfterSaleEvent(AfterSaleEventVO eventVO) throws Exception {
        AfterSaleEvent event = new AfterSaleEvent();
        BeanUtils.copyProperties(eventVO,event);

        // 设置更新时间
        Date now = new Date();
        event.setUpdateTime(now);

        return eventDao.update(event);
    }

    /**
     * 获取系统订单对应售后事件列表 wangxing 2017-12-04 add
     * 
     * @param orderId
     * @return
     * @throws Exception
     */
    public List<AfterSaleEventVO> queryEventListByOrderId(String orderId) throws Exception {
        List<AfterSaleEventVO> returnObject = null;
        if (StringUtils.isNotBlank(orderId)) {
            returnObject = eventDao.selectByOrderId(orderId);
        }
        return returnObject;
    }

}
